package com.achieve.mqtt.controller;

import com.achieve.mqtt.domain.MqttConfigProperties;
import com.achieve.mqtt.service.MqttMessageSender;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Map;

@RestController
@RequestMapping("/api/lamp")
@Slf4j
public class LampApiController {
    @Autowired
    private MqttMessageSender mqttMessageSender;
    @Autowired
    private MqttConfigProperties mqttConfigProperties;
    @Autowired
    private CloseableHttpClient httpClient;

    @GetMapping(value = "{deviceId}/{status}")
    public String sendStatusLampMsg(@PathVariable String deviceId, @PathVariable Integer status) {
        Map<String, Object> map = Map.of("deviceId", deviceId, "status", status);
        String json = JSON.toJSONString(map);
        mqttMessageSender.sendMsg("iot/lamp/server/line", json);
        return "ok";
    }

    /**
     * 查询设备是否在线，v4和v5版本返回值不同；认证使用Basic方式
     * @param clientId
     * @return
     */
    @GetMapping(value = "online/{clientId}")
    public boolean isClientOnline(@PathVariable String clientId) {
        String apiUrl = mqttConfigProperties.getApiUrl() + "/api/v5/clients/" + clientId;
        HttpGet httpGet = new HttpGet(apiUrl);
        httpGet.setHeader(HttpHeaders.ACCEPT, "application/json");
        String auth = Base64.getEncoder()
                .encodeToString((mqttConfigProperties.getApiKey() + ":" + mqttConfigProperties.getSecretKey()).getBytes());
        httpGet.setHeader("Authorization", "Basic " + auth);

        try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
            int statusCode = response.getStatusLine().getStatusCode();
            HttpEntity entity = response.getEntity();

            if (statusCode == HttpStatus.SC_OK && entity != null) {
                String json = EntityUtils.toString(entity, StandardCharsets.UTF_8);
                log.info("isClientOnline data {}", json);
                JSONObject jsonObject = JSON.parseObject(json);
                return jsonObject.getBoolean("connected");
            } else if (statusCode == HttpStatus.SC_NOT_FOUND) {
                return false; // 设备不存在
            } else {
                throw new RuntimeException("EMQX API 请求失败: HTTP " + statusCode);
            }
        } catch (IOException e) {
            throw new RuntimeException("网络通信异常", e);
        }
    }
}
